import { useEffect } from 'react';
import { Table, Button,  message, Popconfirm, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import {
  getScriptList,
  downloadScript,
  offScript,
} from '@/services/striptManage';
import { useSet } from '@/utils/hooks';
import ScriptUploadForm from './scriptUpload';

const ScriptManage: React.FC = () => {
  const [state, setState] = useSet({
    loading: false,
    dataSource: [],
    total: 0,
    pageNum: 1,
    pageSize: 10,
    open: false,
    striptConfig: {},
    type: 'add',
  });

  const { loading, dataSource, total, pageNum, pageSize, open, striptConfig, type } = state;

  // 获取脚本列表
  const getScriptListData = (params?: any) => {
    if (loading) return;
    setState({ loading: true });
    getScriptList({
      pageNum,
      pageSize,
      ...params,
    })
      .then((res) => {
        if (res) {
          setState({
            dataSource: res.rows,
            total: res.total,
          });
        }
      })
      .catch((err) => {
        console.log(err, 'err');
      })
      .finally(() => {
        setState({ loading: false });
      });
  };

  // 下载脚本
  const handleDownload = (record: any) => {
    downloadScript({ encryptedData: record.scriptId }).then((res) => {
      const url = window.URL.createObjectURL(new Blob([res]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', record.scriptName);
      document.body.appendChild(link);
      link.click();
    });
  };

  const columns: any = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
    },
    {
      title: '脚本名称',
      key: 'scriptName',
      dataIndex: 'scriptName',
    },
    {
      title: '脚本URL',
      key: 'scriptUrl',
      dataIndex: 'scriptUrl',
    },
    {
      title: '脚本ID',
      key: 'scriptId',
      dataIndex: 'scriptId',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      render: (time: number) => time && moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '状态',
      key: 'scriptStatus',
      dataIndex: 'scriptStatus',
    },
    {
      title: '操作',
      key: 'action',
      render: (record: any) => (
        <Space>
          <Button
            type="link"
            size="small"
            onClick={() => setState({ striptConfig: record, open: true, type: 'edit' })}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => setState({ striptConfig: record, open: true, type: 'view' })}
          >
            查看
          </Button>
          <Popconfirm
            title="确认下架脚本吗？"
            onConfirm={() => {
              offScript({ scriptId: record?.scriptId }).then(() => {
                message.success('下架脚本成功');
                getScriptListData();
              });
            }}
          >
            <Button type="link" danger size="small">
              下架
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    getScriptListData();
  }, []);


  return (
    <div>
      <div style={{ marginBottom: 12 }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setState({ open: true, type: 'add' })}
        >
          上传脚本
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          total,
          showTotal: (total) => `共 ${total} 条数据`,
          current: pageNum,
          pageSize,
          onChange: (page, pageSize) => {
            setState({ pageNum: page, pageSize });
            getScriptListData({
              pageNum: page,
              pageSize,
            });
          },
        }}
      />

      <ScriptUploadForm
        open={open}
        onClose={() => {
          setState({ open: false, striptConfig: {}, type: 'add' });
        }}
        refresh={getScriptListData}
        data={striptConfig}
        type={type}
      />
    </div>
  );
};

export default ScriptManage;
